<template>
  <!-- 准备一个有宽高的dom ———— 其他内容从父组件传过来 -->
  <div :id="uid" :style="style" class="zsywh"></div>
</template>
<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  nextTick,
  watch,
  onUnmounted,
  shallowRef,
} from "vue";
import * as echarts from "echarts";
const props = defineProps({
  dataSource: {
    type: Object,
    default: null,
    required: true,
  },
  canvasWidth: {
    type: String,
    default: "",
    required: true,
  },
  canvasHeight: {
    type: String,
    default: "",
    required: true,
  },
});
const uid = ref("");
const myChart = shallowRef(null);
// 时间戳+随机字符
uid.value = new Date().getTime() + Math.random().toString(32).slice(2, 10);
// console.log("uid:", uid.value);

let style = computed(() => ({
  width: props.canvasWidth,
  height: props.canvasHeight,
}));
// console.log("style:", style.value);

const init = () => {
  // 基于准备好的dom，初始化echarts实例
  myChart.value = echarts.init(document.getElementById(uid.value));
  // 绘制图表
  myChart.value.setOption(props.dataSource);
  // myChart.value.on("click", (params) => {
  //   console.log(params);

  //   // if (params.componentType == "markPoint") {
  //   // if (params.name == "aa") {
  //   //   let indexNum = params.data.coord[0]; //可以获取到目前点击的点的index值
  //   //   //aa气泡点点击的处理方法
  //   // } else if (params.name == "bb") {
  //   //   //bb气泡点点击的处理方法
  //   // }
  //   // }
  // });
};
const resizeChart = () => {
  if (myChart.value) {
    myChart.value.resize();
  }
};
onMounted(() => {
  // nextTick(() => {
  //     init()
  // })
  init();
  window.addEventListener("resize", resizeChart);
});
watch(
  () => props.dataSource,
  (newVal, oldVal) => {
    init();
  },
  { deep: true }
);
onUnmounted(() => {
  // 清理资源
  if (myChart.value) {
    myChart.value.dispose();
  }
  window.removeEventListener("resize", resizeChart);
});
</script>
<style scoped>
.zsywh {
  width: 100%;
  height: 100%;
}
</style>